package com.gitee.zhangchenyan.takin.service;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gitee.zhangchenyan.takin.auth.AuthUserService;

import java.time.LocalDateTime;

@Component
public class TakinMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private AuthUserService authUserService;

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject, "creationTime", LocalDateTime::now, LocalDateTime.class);
        if (userId != null) {
            this.strictInsertFill(metaObject, "creatorId", () -> userId, Long.class);
        }
        this.strictInsertFill(metaObject, "isDeleted", () -> 0, Integer.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserId();
        if (userId != null) {
            this.strictUpdateFill(metaObject, "lastModifierId", () -> userId, Long.class);
        }
        this.strictUpdateFill(metaObject, "lastModificationTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)

    }

    private Long getUserId() {
        return authUserService.getId();
    }
}
